<template>
    <view>
        <!-- pages/mine/mine.wxml -->
        <view class="topbox">
            <cu-custom :isShowicon="false" :isBack="true">
                <view slot="backText" @tap="gotoSign">
                    <image src="/static/images/topbtn.png" mode="widthFix" style="width: 200rpx"></image>
                </view>
                <view slot="content"><text class="text-white">我的</text></view>
            </cu-custom>
        </view>
        <view class="minetop padding-top-lg padding-lr">
            <view class="flex align-center justify-between">
                <view class="cu-avatar xl round" :style="'background-image:url(' +(getuser? getuser.avatar:'') + ');'" ></view>
                <view class="userInfo flex-sub margin-left">
                    <view v-if="!getuser" class="text-xl" @tap="getCode">点击登录</view>

                    <view v-if="getuser" class="text-xl">
                        {{ getuser.nickname }}
                        <view class="cu-tag bg-yellow sm" v-if="getuser.vip_date != '未开通会员'">VIP</view>
                        <view class="mymodalclose action text-gray" @tap="userTopup">
                            <text class="cuIcon-playfill text-gray"></text>
                            <text>切换账户</text>
                        </view>
                    </view>
                    <view class="margin-top-sm text-sm">
                        UID:{{ getuser?getuser.uid : '0' }}
                        <text class="margin-left-sm">K币:{{  getuser?getuser.virtual_currency : 0 }}</text>
                    </view>
                </view>
                <view class="topupbox" v-if="!ios">
                    <view class="topupbtn" @tap="openTopup">充值K币</view>
                </view>
            </view>
            <view v-if="!ios">
                <view class="vipbox" v-if="(getuser?getuser.vip_date:'未开通会员') === '未开通会员'">
                    <image src="/static/images/vip.png" mode="widthFix"></image>
                    <label>365元全部短剧随心看365天</label>
                    <view class="vipbtn" @tap="viptopip">开通会员</view>
                </view>
                <view class="vipbox" v-else>
                    <image src="/static/images/vipon.png" mode="widthFix"></image>
                    <label>到期时间：{{ getuser.vip_date }}</label>
                    <view class="vipbtn" @tap="viptopip">续费会员</view>
                </view>
            </view>
        </view>
        <view class="cu-list menu margin-top margin-bottom-xl radius">
            <view class="cu-item arrow">
                <navigator class="content" url="#" data-page="/pages/mine/myafter/myafter" @tap="gotoPage" hover-class="none">
                    <text class="cuIcon-recordfill lg text-red"></text>
                    <text class="text-black text-bold">我的追剧</text>
                </navigator>
            </view>
            <view class="cu-item arrow">
                <navigator class="content" url="#" data-page="/pages/mine/mywatch/mywatch" @tap="gotoPage" hover-class="none">
                    <text class="cuIcon-timefill lg text-orange"></text>
                    <text class="text-black text-bold">我的观看</text>
                </navigator>
            </view>
            <view class="cu-item arrow">
                <navigator class="content" url="#" data-page="/pages/mine/order/order" @tap="gotoPage" hover-class="none">
                    <text class="cuIcon-rechargefill lg text-yellow"></text>
                    <text class="text-black text-bold">我的充值</text>
                </navigator>
            </view>
            <view class="cu-item arrow">
                <navigator class="content" url="/pages/mine/sale/sale" hover-class="none">
                    <text class="cuIcon-sponsorfill lg text-olive"></text>
                    <text class="text-black text-bold">我的消费</text>
                </navigator>
            </view>
            <!-- <view class="cu-item arrow">
      <navigator class="content" url="/pages/about/about/about" hover-class="none">
        <text class="cuIcon-favorfill lg text-cyan"></text>
        <text class="text-black text-bold">收藏小程序</text>
      </navigator>
    </view> -->
            <view class="cu-item arrow">
                <navigator class="content" url="/pages/service/service" hover-class="none">
                    <text class="cuIcon-communityfill lg text-pink"></text>
                    <text class="text-black text-bold">联系客服</text>
                </navigator>
            </view>
        </view>
        <view :class="'cu-modal  bottom-modal ' + (userModal == true ? 'show' : '') + ' mymodal'" @tap="hideModal" v-if="getuser">
            <view class="cu-dialog" catchtap >
                <view class="cu-bar cztopbox padding-right-sm">
                    <view class="action text-black">切换账户</view>
                </view>
                <view class="padding-lr-sm align-center justify-between xsgdun">
                    <view
                        class="flex align-center justify-between padding-sm"
                        @tap="userxhModal"
                        :data-channel_id="item.channel_id"
                        :data-token="item.token"
                        v-for="(item, index) in getuser.applist"
                        :key="index"
                    >
                        <view class="cu-avatar xl round" :style="'background-image:url(' + item.avatar + ');'" v-if="item"></view>

                        <view class="userInfo flex-sub text-left margin-left">
                            <view class="text-xl">
                                {{ item.nickname }}
                                <view class="cu-tag bg-yellow sm" v-if="item.vip_date != '未开通会员'">VIP</view>
                            </view>
                            <view class="margin-top-sm text-sm">
                                UID:{{ item.uid || '0' }}
                                <text class="margin-left-sm">K币:{{ item.virtual_currency || 0 }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view :class="'cu-modal bottom-modal ' + (showModal == true ? 'show' : '') + ' mymodal'" @tap="hideModal" v-if="getuser">
            <view class="cu-dialog" catchtap>
                <view class="cu-bar cztopbox padding-right-sm">
                    <view class="action text-black">K币充值</view>
                    <view class="action text-gray">
                        账户余额：
                        <text class="text-black">{{ getuser.virtual_currency }}</text>
                        K币
                    </view>
                </view>
                <view class="padding padding-bottom-xs padding-lr-xl flex align-center justify-between flex-wrap">
                    <view
                        :class="'topupitem  flex flex-direction align-center justify-between ' + (item.is_vip == 1 ? 'vip' : '')"
                        @tap="checkPay"
                        :data-id="item.id"
                        v-for="(item, index) in product"
                        :key="index"
                    >
                        <view class="pushbox" v-if="item.corner_mark">{{ item.corner_mark }}</view>

                        <view class="sale text-bold text-xl flex align-center">{{ item.pay_money }}元</view>

                        <view class="kbi text-sm margin-top-xs">
                            <text v-if="item.sub_title">{{ item.sub_title }}{{ item.virtual_currency_gift != 0 ? '+送' + item.virtual_currency_gift + '币' : '' }}</text>
                            <text v-if="item.sub_title_end" class="margin-left-xs" style="color: rgb(250, 96, 130)">{{ item.sub_title_end }}</text>
                        </view>

                        <view class="song flex align-center justify-center text-sm margin-top-xs text-red">
                            {{ item.remark }}
                        </view>
                    </view>
                </view>
            </view>
        </view>

<!--        <bar :tabon="4"></bar> -->
    </view>
</template>

<script>
import bar from '../../components/Bar';
// pages/mine/mine.js
const _api = require('../../utils/api.js');
const apiurl = require('../../utils/apiurl/public.js');
export default {
    components: {
        bar
    },
    data() {
        return {
            showModal: false,
            userModal: false,
            userInfo: null,
            product: [],

            //充值项目
            getuser: null,

            //从接口获取的用户信息
            order: null,

            apisum: 0,
            ios: false,
            showPay: false
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let userInfo = uni.getStorageSync('userInfo');
        let _this = this;
        let system = uni.getSystemInfoSync().system.toLowerCase().includes('ios');
        this.setData({
            userInfo: userInfo,
            ios: system
        });
        this.getCode();
        this.getUserinfo();
        this.getProduct();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        getCode() {
            uni.getUserProfile({
                desc: '用于完善会员资料',
                // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (userres) => {
                    console.log(userres.userInfo);
                    uni.setStorageSync('wxuserInfo', JSON.stringify(userres.userInfo));
                    let wxuserInfo = userres.userInfo;
                    let sex = wxuserInfo.gender == 0 ? '男' : '女';
                    uni.login({
                        success: (res) => {
                            var code = res.code;
                            if (code) {
                                uni.getUserInfo({
                                    success: (ures) => {
                                        _api.post(apiurl.login, {
                                            js_code: code,
                                            encryptedData: ures.encryptedData,
                                            iv: ures.iv
                                        }).then((loginres) => {
                                            console.log(232323);
                                            console.log(loginres.data);
                                            uni.setStorageSync('token', loginres.data.data.token);
                                            _api.post('index/user/info_edit', {
                                                nickname: wxuserInfo.nickName,
                                                avatar: wxuserInfo.avatarUrl,
                                                sex: sex
                                            }).then((infores) => {});
                                            this.getUserinfo();
                                        });
                                    }
                                });
                            }
                        }
                    });
                }
            });

            //   wx.getUserProfile({
            //     desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            //     success: (ress) => {
            //         console.log(ress);
            //       var encryptedData=ress.encryptedData
            //       var iv=ress.iv
            //       wx.setStorageSync('userInfo', ress.userInfo)
            //       wx.login({
            //         success:res=>{
            //           var code=res.code
            //           _api.post(apiurl.login,{js_code:code,encryptedData:encryptedData,iv:iv}).then(loginres=>{
            //             console.log(232323);
            //             console.log(loginres.data);
            //             wx.setStorageSync('token', loginres.data.data.token)
            //             let userInfo=wx.getStorageSync('userInfo')
            //             this.setData({
            //                 userInfo:userInfo
            //             })
            //           })
            //         }
            //       })
            //     }
            //   })
        },

        openTopup() {
            //打开充值框
            this.setData({
                showModal: true
            });
            this.getCode();
        },

        userTopup() {
            //打开充值框
            this.setData({
                userModal: true
            });
        },

        viptopip() {
            //打开充值框
            this.getCode();
            let id = {
                currentTarget: {
                    dataset: {
                        id: 60
                    }
                }
            };
            this.checkPay(id);
        },

        hideModal() {
            //关闭充值框
            this.setData({
                showModal: false,
                userModal: false
            });
        },

        userxhModal(e) {
            uni.showLoading({
                title: '切换账户中...'
            });
            uni.setStorageSync('channelid', e.currentTarget.dataset.channel_id);
            uni.setStorageSync('token', '');
            uni.login({
                success: (res) => {
                    var code = res.code;
                    if (code) {
                        uni.getUserInfo({
                            success: (ures) => {
                                _api.post(apiurl.login, {
                                    js_code: code,
                                    encryptedData: ures.encryptedData,
                                    iv: ures.iv
                                }).then((loginres) => {
                                    console.log('loginres', loginres);
                                    if (loginres.data) {
                                        uni.setStorageSync('token', loginres.data.data.token);
                                    }
                                    this.getUserinfo();
                                });
                            }
                        });
                    }
                }
            });
            this.hideModal();
        },

        gotoSign() {
            uni.navigateTo({
                url: '/pages/signin/signin'
            });
        },

        gotoPage(e) {
            var value = uni.getStorageSync('token');
            if (value) {
                uni.navigateTo({
                    url: e.currentTarget.dataset.page
                });
            } else {
				
                this.getCode();
            }
        },

        getProduct() {
            //获取充值项目
            _api.get(apiurl.rechargeitem).then((res) => {
                if (res.data.code == 0) {
                    this.setData({
                        product: res.data.data
                    });
                }
            });
        },

        getUserinfo() {
            //获取用户信息
            _api.get(apiurl.userinfo).then((res) => {
                uni.hideLoading();
                if (res.data.code == 0) {
                    this.setData({
                        getuser: res.data.data
                    });
                    uni.setStorageSync('getuser', res.data.data);
                    this.select_order();
                }
            });
        },

        select_order() {
            _api.get(apiurl.selectorder).then((res) => {
                if (res.data.code == 0) {
                    this.setData({
                        order: res.data.data
                    });
                    uni.setStorageSync('getuser', res.data.data);
                }
            });
        },

        wxorder(id) {
            let _this = this;
            console.log(id);
            //apiurl.wxorder
            _api.post(apiurl.wxorder, {
                orderid: id
            }).then((res) => {
                if (res.data.code == 0) {
                    let data = res.data.data.order;
                    if (data.status) {
                        setTimeout(() => {
                            _this.wxorder(id);
                        }, 2000);
                    }
                    uni.hideLoading();
                    _this.setData({
                        showPay: false
                    });
                    _this.hideModal();
                    _this.getUserinfo();
                }
            });
        },

        checkPay(e) {
            //选择充值的项
            let id = e.currentTarget.dataset.id;
            let _this = this;
            this.getCode();
            _api.post(apiurl.ordercreate, {
                id: id
            }).then((res) => {
                if (res.data.code == 0) {
                    const SDKVersion = uni.getSystemInfoSync().SDKVersion;
                    if (_this.compareVersion(SDKVersion, '2.19.2') >= 0 || uni.canIUse('requestVirtualPayment')) {
                        let da = res.data.data;
                        let orderid = JSON.parse(da.signData).outTradeNo;
                        uni.requestVirtualPayment({
                            signData: JSON.stringify(JSON.parse(da.signData)),
                            paySig: da.paySig,
                            signature: da.signature,
                            mode: da.mode,
                            success(res) {
                                _this.wxorder(orderid);
                            },
                            fail({ errMsg, errCode }) {
                                console.error(errMsg, errCode);
                            }
                        });
                    } else {
                        console.log('当前用户的客户端版本不支持 wx.requestVirtualPayment');
                    }
                } else if (res.data.code == 103) {
                    this.getCode();
                }
            });
        },

        compareVersion(_v1, _v2) {
            if (typeof _v1 !== 'string' || typeof _v2 !== 'string') {
                return 0;
            }
            const v1 = _v1.split('.');
            const v2 = _v2.split('.');
            const len = Math.max(v1.length, v2.length);
            while (v1.length < len) {
                v1.push('0');
            }
            while (v2.length < len) {
                v2.push('0');
            }
            for (let i = 0; i < len; i++) {
                const num1 = parseInt(v1[i], 10);
                const num2 = parseInt(v2[i], 10);
                if (num1 > num2) {
                    return 1;
                } else if (num1 < num2) {
                    return -1;
                }
            }
            return 0;
        }
    }
};
</script>
<style>
/* pages/mine/mine.wxss */
page {
    background: #ffffff;
    padding-bottom: 120rpx;
}
.topbox {
    background: #1cbbb4;
}
.minetop {
    background: #1cbbb4;
    color: #ffffff;
    padding-top: 200rpx;
    padding-bottom: 20rpx;
}
.mymodalclose text {
    transform: rotate(90deg);
    color: #fff;
}
.mymodalclose {
    display: inline-block;
    font-size: 24rpx;
    padding-bottom: 15rpx;
}
.cuIcon-playfill {
    display: inline-flex;
}
.vipbox {
    height: 100rpx;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 33rpx;
}
.topupbox {
    flex: 0 0 190rpx;
    padding-top: 55rpx;
    margin-right: -10rpx;
}
.topupbtn {
    width: 190rpx;
    height: 70rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(to right, #fdf46d, #fdb81d);
    border-radius: 35rpx;
    color: #3f1f00;
    text-shadow: #fff99a 0px 1px 1px;
}
.vipbox {
    width: 670rpx;
    margin: 40rpx auto 0 auto;
    padding-left: 20rpx;
}
.vipbox image {
    display: block;
    width: 50rpx;
}
.vipbox label {
    color: #000;
    font-size: 26rpx;
    font-family: fantasy;
}
.vipbtn {
    width: 150rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(to right, #000, #000);
    border-radius: 35rpx;
    color: #3f1f00;
    text-shadow: #fff99a 0px 1px 1px;
    right: 0;
    position: absolute;
    margin-top: -62rpx;
    margin-right: 58rpx;
    color: #fff;
    font-size: 26rpx;
}
.mymodal {
    bottom: 100rpx;
}
.topupitem {
    width: 46%;
    position: relative;
    margin-bottom: 30rpx;
    border-radius: 12rpx;
    height: 186rpx;
    background: #ffffff;
    border: #e8e8e8 solid 2rpx;
}
.pushbox {
    position: absolute;
    font-size: 10px;
    color: #ffffff;
    line-height: 34rpx;
    height: 34rpx;
    background: #1cbbb4;
    padding: 0 12rpx;
    border-radius: 17rpx 0 0 17rpx;
    top: 0;
    right: 0;
}
.sale {
    color: #333333;
    height: 60rpx;
    padding-top: 40rpx;
}
.topupitem.zk {
    border: #fb151c solid 4rpx;
    background: #ffcd52;
}
.topupitem.vip {
    border: #1cbbb4 solid 4rpx;
    background: rgba(250, 96, 130, 0.1);
}
.song {
    color: #1cbbb4;
    font-weight: bold;
    height: 50rpx;
    width: 100%;
    background: #1cbbb41f;
}
.topupitem.vip .sale {
    color: #333333;
}
.topupitem.vip .song {
    color: #ffffff !important;
    background: #1cbbb4;
}
.iconbox {
    position: absolute;
    width: 90rpx;
    height: 90rpx;
    top: 0;
    right: 0;
}
.cztopbox {
    background: linear-gradient(to bottom, rgb(0 150 136 / 21%), #ffffff);
}
.cu-dialog {
    background-color: #ffffff !important;
}
</style>
